package logic

import (
	"context"
	"gorm.io/gorm"
	"strconv"
	"time"
	"weee/common"
	"weee/models"

	"weee/orderrpc/internal/svc"
	"weee/orderrpc/orderrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenerateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateOrderLogic {
	return &GenerateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GenerateOrder todo: 生成订单
func (l *GenerateOrderLogic) GenerateOrder(in *orderrpc.GenerateOrderRequest) (*orderrpc.GenerateOrderResponse, error) {
	// todo: add your logic here and delete this line
	user, _ := models.GetUserInfo(models.User3{
		Model: gorm.Model{ID: uint(in.UserId)},
	})
	if user.ID == 0 {
		return &orderrpc.GenerateOrderResponse{
			Code: 400,
			Msg:  "用户不存在",
		}, nil
	}
	goods, _ := models.GetGoodsInfo(models.Goods3{
		Model: gorm.Model{ID: uint(in.GoodsId)},
	})
	if goods.ID == 0 {
		return &orderrpc.GenerateOrderResponse{
			Code: 400,
			Msg:  "技师不存在",
		}, nil
	}
	//todo: 生成订单
	code := common.RandomNum()
	times := time.Now().Unix()
	orderSn := strconv.Itoa(int(times)) + code
	order := models.Order3{
		Userid:  int(in.UserId),
		OrderSn: orderSn,
		Name:    goods.Name,
		Price:   goods.Price,
		Times:   goods.Times,
		PayType: "",
		Status:  "未支付",
	}
	_, err := models.GenerateOrder(order)
	if err != nil {
		return &orderrpc.GenerateOrderResponse{
			Code: 400,
			Msg:  "订单生成失败",
		}, nil
	}
	return &orderrpc.GenerateOrderResponse{
		Code: 200,
		Msg:  "订单生成成功",
	}, nil
}
